package com.ellecity06.cwhiskymall.ui.login.forget

import androidx.lifecycle.viewModelScope
import com.ellecity06.common.base.BaseMviViewModel
import com.ellecity06.common.ktx.md5Encrypt
import com.ellecity06.common.ktx.postEvent
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.cwhiskymall.bean.request.ForgetPwdRequest
import com.ellecity06.cwhiskymall.bean.request.SendSmsCodeRequest
import com.ellecity06.cwhiskymall.http.ServerConfig
import com.ellecity06.cwhiskymall.http.request
import kotlinx.coroutines.launch

/**
 *@author joe
 *@data 2024/10/29
 *@describe
 */
class ForgetPwdViewModel : BaseMviViewModel<ForgetPwdState, ForgetIntent>() {
    override suspend fun collectIntent(it: ForgetIntent) {
        when (it) {
            // 获取图片验证码
            is ForgetIntent.SendSmsCode -> fetchSmsCode(it.imageCode, it.phone)
            is ForgetIntent.ForgetPwd -> register(it)
            is ForgetIntent.GetPicCode -> getPicCode(it.phone)
            else -> {}
        }
    }

    private fun register(it: ForgetIntent.ForgetPwd) {
        if (it.phone.isEmpty() || it.phone.length < 11) {
            ToastUtils.show("请输入正确的手机号")
            return
        }
        if (it.code.isEmpty()) {
            ToastUtils.show("请输入验证码")
            return
        }
        if (it.password.isEmpty()) {
            ToastUtils.show("请输入密码")
            return
        }
        if (it.rePassword.isEmpty()) {
            ToastUtils.show("请再次输入密码")
            return
        }
        if (it.password != it.rePassword) {
            ToastUtils.show("两次密码不一致")
            return
        }
        request(
            api = { forgetPwd(ForgetPwdRequest(it.code, it.password?.md5Encrypt(), it.phone, 1)) },
            success = {
                mState.postEvent(ForgetPwdState.ForgetPwdSuccess)
            })
    }

    private fun fetchSmsCode(imageCode: String, phone: String) {
        if (phone.isEmpty() || phone.length < 11) {
            ToastUtils.show("请输入正确的手机号")
            return
        }
        if (imageCode.isEmpty()) {
            ToastUtils.show("请输入图形验证码")
            return
        }
        request(api = { smsCode(SendSmsCodeRequest(3, imageCode, phone)) }, success = {
            mState.postEvent(ForgetPwdState.SmdCodeSuccess)
        }, error = {
            showToast(it.message)
            getPicCode(phone)
        })
    }

    private fun getPicCode(phone: String) {
        if (phone.isEmpty() || phone.length < 11) {
            ToastUtils.show("请输入正确的手机号")
            return
        }
        val url =
            "${ServerConfig.baseHost}api/web/auth/sms/sendpicVerifyCode?phone=${phone}&timestamp=${System.currentTimeMillis()}"
        viewModelScope.launch {
            mState.postEvent(ForgetPwdState.GetPicCodeSuccess(url))
        }

    }

}